package com.ruoyi.common.utils;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;

import java.util.Map;
import java.util.Properties;


/**
 * @Author: wwy
 * @Date: 2021/1/6 13:37
 */
public class SmsUtils {

    public static boolean sendMessageAli(String phone,String message,String templateCode){
        Properties aliProperties = PropertiesReadUtil.getAliProperties();
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", String.valueOf(aliProperties.get("accessKeyId")), String.valueOf(aliProperties.get("accessKeySecret")));
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", String.valueOf(aliProperties.get("SignName")));
        request.putQueryParameter("TemplateCode", templateCode);
        request.putBodyParameter("TemplateParam",message);
        try {
            CommonResponse response = client.getCommonResponse(request);
            String data = response.getData();
            Map<String,Object> dataMap = JSONObject.parseObject(data, Map.class);
            String code = String.valueOf(dataMap.get("Code"));
            if("OK".equals(code)){
                //成功
                return true;
            }
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return false;
    }

}
